<template>
      <el-autocomplete
        v-model="state1"
        :fetch-suggestions="querySearch"
        clearable
        style="width:100%"
        :placeholder="placeholder"
        :popper-append-to-body="false"
        @select="changeValue"
      />
</template>

<script setup>

const state1 = ref('')

const props = defineProps({
  // 列表
  list: {
    type: Array,
    default: [],
  },

  // 提示文字
  placeholder: {
    type: String,
    default: '请输入内容'
  },

  // 选择内容
  changeValue: {
    type: Function,
    default: () => {}
  },

  // 选择内容
  inputName: {
    type: String,
    default: ''
  },

  // 选择内容
  inputValue: {
    type: Function,
    default: () => {}
  },

});
const restaurants = ref([])
watch(() => props.list, val => {
  restaurants.value = val || []
},{ deep: true, immediate: true });

watch(() => props.inputValue, val => {
  if(val){
    for(let i = 0; i < restaurants.value.length; i++){
      if(restaurants.value[i][props.inputName] == props.inputValue){
        state1.value = restaurants.value[i].value
      }
    }
  }else{
    state1.value = ''
  }
},{ deep: true, immediate: true });

const querySearch = (queryString, cb) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  cb(results)
}
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
      // restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}

const handleSelect = (item) => {
  changeValue(item)
}
</script>

<style scoped lang="scss">
.el-popper[x-placement^=bottom]{
  width: 100%;
}
</style>